package com.ericsson.springauth.service;

import com.ericsson.springauth.model.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 * Created by IntelliJ IDEA.
 * User: lbonacina
 * Date: 25/07/11
 * Time: 15.59
 */
@Service("userService")
public class UserServiceImpl extends ServiceDefaultImpl implements UserService {

// ------------------------ INTERFACE METHODS ------------------------
// --------------------- Interface UserService ---------------------
    @Override
    @Transactional(readOnly = true)
    @SuppressWarnings(value = "unchecked")
    public List<User> findAll() {
        return (List<User>) getCurrentSession().createCriteria(User.class).list();
    }

    @Override
    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {

        Session session = getCurrentSession();
        User operator = (User) session.createCriteria(User.class).add(Restrictions.eq("username", username)).uniqueResult();
        if (operator == null) {
            throw new UsernameNotFoundException("User not found.");
        }
        return operator;
    }

    /**
     * @return the logged User
     *         NB : questo metodo non è @Transactional perchè non accede al DB
     */
    @Override
    public User getLoggedUser() {

        return (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }
}
